package com.example.demo.web.controller;

import com.example.demo.domain.User;
import com.example.demo.service.IUserService;
import com.example.demo.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Controller
public class FileUpload {

    @Autowired
    private IUserService userService;

    @RequestMapping(value="/file/uploadFile", method= RequestMethod.POST)
    @ResponseBody
   public AjaxResult upload(HttpServletRequest req, Integer id, @RequestParam("file") MultipartFile file){
        System.out.println("上传文件用户...."+id);
        try {
            if(file.isEmpty()){
                return new AjaxResult("文件为空");
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //获取项目相对路径
            String fileMkDir = System.getProperty("user.dir");
            String filePath = fileMkDir+"\\src\\main\\resources\\static\\upload\\";
            System.out.println("文件路径:"+filePath);
            String newFileName= UUID.randomUUID().toString()+suffixName;
            String path = filePath + newFileName;
            File dest = new File(path);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }

            file.transferTo(dest);

            //更新用户表的头像
            User user = new User();
            user.setId(Long.parseLong(id+""));
            user.setHeadImg("/upload/"+newFileName);
            userService.updateUserHeadImg(user);

            return new AjaxResult();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
